package com.jisf.driver.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.jisf.driver.entity.enumtype.IsReadEnum;
import com.jisf.driver.entity.po.Chat;
import com.jisf.driver.exception.SystemException;
import com.jisf.driver.mapper.ChatMapper;
import com.jisf.driver.response.ResultCode;
import com.jisf.driver.service.IChatService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jisf.driver.utils.UserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author jisf
 * @since 2022-05-06
 */
@Service
public class ChatServiceImpl extends ServiceImpl<ChatMapper, Chat> implements IChatService {

    @Autowired
    private ChatMapper chatMapper;

    /**
     * 所有聊天记录
     * @param id
     * @return
     */
    @Override
    public List<Chat> chatRecords(Integer id) {
        try {
            Integer userid = UserUtil.userIdThreadLocal.get();
            QueryWrapper<Chat> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("initiator", userid).eq("receiver", id)
                    .or(QueryWrapper -> QueryWrapper.eq("initiator", id).eq("receiver", userid));
            queryWrapper.orderByAsc("send_time");
            List<Chat> chats = chatMapper.selectList(queryWrapper);
            setIsRead(id);
            return chats;
        }catch (Exception e){
            throw new SystemException(e);
        }
    }

    /**
     * 设置已读
     * @param id 消息发送者id
     */
    @Override
    public void setIsRead(Integer id) {
        try {
            Integer userid = UserUtil.userIdThreadLocal.get();
            UpdateWrapper<Chat> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("receiver", userid).eq("initiator", id).eq("is_read", IsReadEnum.UNREAD);
            Chat chat = new Chat();
            chat.setIsRead(IsReadEnum.READ);
            chatMapper.update(chat, updateWrapper);
        }catch (Exception e){
            throw new SystemException(e);
        }
    }

    /**
     * 发送消息
     * @param chat
     */
    @Override
    public ResultCode sendMessage(Chat chat){
        try {
            chat.setIsRead(IsReadEnum.UNREAD);
            int insert = chatMapper.insert(chat);
            if (insert != 0){
                return ResultCode.CHAT_SEND_MESSAGE_SUCCESS;
            }else {
                return ResultCode.CHAT_SEND_MESSAGE_FAILED;
            }
        }catch (Exception e){
            throw new SystemException(e);
        }
    }
}
